<script>
import { mapActions, mapState, mapMutations } from "vuex";
import { queryUserInfo } from "@/services/user";
import { queryFriendsList } from "@/services/friends";
import { queryGroupList, queryModuleGroupList } from "@/services/group";
import {
  formatUserInfo,
  getDefaultColor,
  setIsInWebview,
  isUpdateVersion,
} from "@/utils/index";
import { allWatchMessages } from "@/utils/RongIM";
import {
  initInterface,
  logoutInterface,
  changeLang,
} from "@/utils/olImInterface.js";
import { gptChatList } from "@/utils/chatGPT.js";
import { countryQueryList } from "@/services/new_api";

import config from "@/config/app.config";
export default {
  onLaunch: function () {
    console.log(this.$RongIMLib, "----");
    this.globalData.gptChatList = gptChatList;
    changeLang();
    console.log("App Launch");
    const Events = this.$RongIMLib.Events;
    console.log(Events);
    this.$RongIMLib.addEventListener(Events.CONNECTING, () => {
      console.log("正在链接...");
      this.changeConnectStatus(1);
    });

    this.$RongIMLib.addEventListener(Events.CONNECTED, () => {
      initInterface(this.rongToken);
      console.log("链接完成");
      this.changeConnectStatus(2);
    });
    this.$RongIMLib.addEventListener(Events.DISCONNECT, (code) => {
      logoutInterface();
      console.log("连接中断，需要业务层进行重连处理 ->", code);
      this.changeConnectStatus(3);
      this.handleConnect();
    });
    this.$RongIMLib.addEventListener(Events.SUSPEND, (code) => {
      console.log("链接中断，SDK 会尝试重连，业务层无需关心");
      console.log(`code -> ${code}`);
      this.changeConnectStatus(4);
    });
    // 监听消息信息
    this.$RongIMLib.addEventListener(
      this.$RongIMLib.Events.MESSAGES,
      allWatchMessages
    );
    // 监听正在输入中的信息
    this.$RongIMLib.addEventListener(
      this.$RongIMLib.Events.TYPING_STATUS,
      (e) => {
        console.log("监听到的输入中状态信息", e);
        this.SET_TYPING(e.status);
        // if (
        //   this.targetId === e.status[0].targetId &&
        //   Number(e.status[0].conversationType) === 1
        // ) {
        //   this.setTyping(this.SET_TYPING);
        // }
      }
    );
    // FIXME
    if (!this.token) {
      // uni.navigateTo({
      //   url: "/pages/login/Login",
      // });
    } else {
      this.getUserInfo();
      this.getFriendsList();
      this.getGroupList();
      this.handleConnect();
      this.getModuleGroupList();
    }
    this.getCountryList();
  },
  globalData: {
    gptChatList: [],
  },
  onShow: function () {
    setIsInWebview();
    isUpdateVersion();
    console.log("App Show");
  },
  onHide: function () {
    console.log("App Hide");
  },
  watch: {
    token(val) {
      if (val && this.rongToken) {
        this.getUserInfo();
        this.getFriendsList();
        this.getGroupList();
        this.handleConnect();
      } else {
        this.changeUserId();
      }
    },
  },
  computed: {
    ...mapState(["token", "rongToken", "userId", "userInfo"]),
  },
  methods: {
    ...mapMutations(["SET_FRIEND_LIST", "SET_TYPING", "setCountryList"]),
    ...mapActions([
      "changeConnectStatus",
      "changeUserId",
      "changeUserInfo",
      "changeGroupList",
    ]),

    async getCountryList() {
      const {
        result: { data },
      } = await countryQueryList();
      console.log(data,'datadatadatadatadatadata');
      this.setCountryList(data);
    },
    async handleConnect() {
      console.log(this.rongToken, "rongToken");
      console.log(config.RongIMAppKey, "RongIMAppKey");
      // 如果没有融云的token,则直接返回,不做连接
      if (!this.rongToken) {
        return;
      }
      const res = await this.$RongIMLib.connect(this.rongToken);
      if (res.code === this.$RongIMLib.ErrorCode.SUCCESS) {
        console.log("链接成功, 链接用户 id 为: ", res.data.userId);
        this.changeUserId(res.data.userId);
        this.changeConnectStatus(2);
      } else {
        console.warn("链接失败, code:", res.code);
      }
    },
    //获取用户信息
    async getUserInfo() {
      const resp = await queryUserInfo();
      if (!resp.success) return;
      const userInfo = resp.result.data;
      this.changeUserInfo(userInfo);
    },
    // 获取好友信息
    async getFriendsList() {
      const resp = await queryFriendsList({
        pageNum: 1,
        pageSize: 999,
      });
      if (!resp.success) return;
      const info = resp.result.rows;
      this.SET_FRIEND_LIST(info);
    },

    //获取其他群组信息
    async getModuleGroupList() {
      const resp = await queryModuleGroupList();
      if (!resp.success) return;
      const { data } = resp.result;
      data.forEach((t) => {
        var info = this.$store.state.moduleGroupInfo[t.moduleType];
        if (info && Array.isArray(info)) {
          let obj = info.find((o) => o.groupId == t.groupId);
          if (!obj) info.push(t);
        } else {
          this.$store.state.moduleGroupInfo[t.moduleType] = [t];
        }
      });
      console.log(this.$store.state.moduleGroupInfo);
    },
    // 获取群组信息
    async getGroupList() {
      const resp = await queryGroupList({
        pageNum: 1,
        pageSize: 999,
      });
      if (!resp.success) return;
      const groupList = resp.result.rows.map((item) => {
        if (
          item.moduleType == 1 &&
          item.userId === this.$store.state.userInfo.userId
        ) {
          item.myName = item.jyRemark || "OMLOOKER";
        } else if (
          item.moduleType == 1 &&
          item.userId !== this.$store.state.userInfo.userId
        ) {
          item.myName = item.groupName;
          item.groupName = item.jyRemark || "OMLOOKER";
          item.avatarCompress =
            item.jyAvatar || "http://www.omlook.com/imol/default_male.png";
        }
        // 交友部分，显示名称逻辑，根据userId进行区分 -- end
        item.defaultName = item.groupName.slice(0, 1);
        item.showAvatar = item.avatar;
        item.defaultColor = getDefaultColor(item.avatarColorCode);
        const data = {
          ...item,
          showAvatar: item.avatar,
          avatarColorCode: item.avatarColorCode,
          defaultColor: getDefaultColor(item.avatarColorCode),
        };
        data.defaultName = data.groupName.slice(0, 1);
        return data;
      });
      this.changeGroupList(groupList);
    },
  },
};
</script>

<style lang="scss">
/*每个页面公共css */
@import "@/uni_modules/uview-ui/index.scss";
/*选择iconfont.css所在的路径*/
@import "./static/font/iconfont.css";

page {
  background-color: #f6f6f6;
}

.avator-font-setting {
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  color: #ffffff;
}
</style>
